package com.zeros.myself.utils;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 判断字符串 on 2017/11/30.
 */

public class StringUtil {

    /**
     * 1. 判断字符串是否不为空
     * @return true-不空、false-空
     */
    public static boolean isNotEmptyOrNull(String s) {
        boolean flag = true;
        if (s == null || s.length() <= 0 || s.equals(""))
            flag = false;
        return flag;
    }


    /**
     * 2. 判断字符串是否为Json
     * 导入:implementation 'com.google.code.gson:gson:2.8.2'
     */
    public static boolean isJson(String json) {
        if (!isNotEmptyOrNull(json))
            return false;

        try {
            if ((json.startsWith("{") && json.endsWith("}")) || (json.startsWith("[") && json.endsWith("]"))) {
                new JsonParser().parse(json);
                return true;
            }
            return false;
        } catch (JsonSyntaxException e) {
//            e.printStackTrace();
            return false;
        }
    }

    /**
     * 2.1 判断字符串是否为Json
     */
    public static boolean isJsonString(String json) {
        boolean isJsonStr;
        try {
            JSONObject jsonObject = new JSONObject(json);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        try {
            JSONArray jsonArray = new JSONArray(json);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        return isJsonStr;
    }

    /**
     * 3. 将json格式的字符串解析成Map对象
     * @param json {"name":"admin","retries":"3fff","testretries":"fffffffff"}
     */
    public static <T> HashMap<String, T> jsonToMap(String json) {
        // 将json字符串转换成jsonObject
        JSONObject jsonObject;
        HashMap<String, T> hashMap = new HashMap<>();
        try {
            jsonObject = new JSONObject(json);
            Iterator iterator = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            String key;
            Object value;
            while (iterator.hasNext()) {
                key = String.valueOf(iterator.next());
                value = jsonObject.get(key);
                if (hashMap.isEmpty() || hashMap == null) {
                    hashMap = new HashMap<>();
                }
                hashMap.put(key, (T) value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    /**
     * 3.1 将Map转换成Json
     * 导入:implementation 'com.google.code.gson:gson:2.8.2'
     */
    public static String mapToJson(Map<String, Object> jsonMap) {
        StringBuilder result = new StringBuilder();//单线程
        result.append("{");
        Iterator<Map.Entry<String, Object>> entryIterator = jsonMap.entrySet().iterator();

        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
//                System.out.println("\n Object Key:" + key);
                String mapJson = mapToJson((Map<String, Object>) value);

                result.append("\"")
                        .append(key)
                        .append("\":")
                        .append(mapJson);
            } else {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                result.append("\"").append(key).append("\":").append(json);
            }

            // 最后一个去掉 逗号
            entryIterator.next();
            if (entryIterator.hasNext()) {
                result.append(",");
            }
        }
        result.append("}");
        return result.toString();
    }

	
	//读取Json文件的工具类--asset资源文件
	public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
	

    public static String toString(Object obj) {
        try {
            return String.valueOf(obj);
        } catch (Exception ex) {
            return "";
        }
    }

}
